<?php
namespace Demo\Controller;

use Think\Controller;
use Common\Model\OpenIdModel as OpenId;
use Common\Model\UserModel as User;

class AuthController extends Controller
{

    /**
     * 授权监测
     */
    public function check()
    {
        session(null);
        try
        {
            $tk = I('tickt');
            $data = base64_decode(I('data'));
            $arr = explode('~~~', $data);
            $timestamp = $arr[0];
            $uid = $arr[1];
            $url = $arr[2];
            
            $tickt = md5(C('url_encode_key') . $timestamp . $uid);
            if ($tk === $tickt)
            {
//                 $time = time();
//                 if (abs($time - $timestamp) >= 15)
//                 {
//                     E("授权失败!", 401);
//                 }
                
                $user = new User();
                $where = array();
                $where['id'] = $uid;
                $user_info = $user->where($where)->find($where);
                
                if ($user_info)
                {
                    // 多账号情况，获取当前账号下的openid
                    $open_obj = new OpenId();
                    $openid = $open_obj->uid2Openid($user_info['id']);
                    $user_info['openid'] = $openid;
                    
                    session('userInfo', $user_info);
                    session('openid', $openid);
                    session('uid', $uid);
                    
                    redirect($url);
                    die();
                } else
                {
                    E("授权失败，请返回微信界面，点击菜单重新开始!", 401);
                }
            }
        } catch (\Exception $e)
        {
            if (IS_AJAX)
            {
                $ret = array();
                $ret['status'] = $e->getCode();
                $ret['msg'] = $e->getMessage();
                $ret['content'] = array();
                $this->ajaxReturn($ret);
            } else
            {
                redirect(U("Error/authfail"));
                die();
            }
        }
    }

    /**
     * 微信网页授权
     */
    public function getinfo()
    {
        try
        {
            $code = I('get.code');
            if ($code)
            {
                // 第二部、授权成功验证授权信息
                $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . C('AppID') . '&secret=' . C('AppSecret') . '&code=' . $code . '&grant_type=authorization_code';
                $rs1 = https_request($url);
                if ($rs1)
                {
                    $rs_obj = json_decode($rs1);
                    $rs = objToArr($rs_obj);
                    if ($rs['errcode'])
                    {
                        my_log('web get openid fail ,errcode: ' . $rs['errcode'] . " , errmsg:" . $rs['errmsg']);
                        E('获取用户失败');
                    }
                    $openid = $rs['openid'];
                    $access_token = $rs['access_token'];
                } else
                {
                    E('获取access_token失败', 403);
                }
            } else if (I("openid"))
            {
                $openid = I("openid");
            }
            
            // 第一步、去微信授权
            if (empty($code) && empty($openid))
            {
                $return_url = urlencode('http://' . C('MAIN_DOMAIN') . $_SERVER["REQUEST_URI"]);
                $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . C('AppID') . '&redirect_uri=' . $return_url . '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
                redirect($url);
                die();
            }
            
            $u = new User();
            $open_obj = new OpenId();
            
            $uid = $open_obj->openid2Uid($openid);
            
            // 数据库找不到该用户信息
            if (empty($uid))
            {
                $info = $u->getWeixinUserDetailInfo2($openid,$access_token);
                if (! $info)
                {
                    my_log('auth getinfo: get user detail info fail~~~' . $openid);
                    E('获取用户失败');
                    return false;
                }
                
                if (! $info['union_id'])
                {
                    my_log('get user union_id  fail');
                    E('获取用户失败');
                    return false;
                }
                
                $info['openid'] = $openid;
                $uid = $u->addUser($info);
            } else
            {
                $where = array();
                $where['id'] = $uid;
                $data = array();
                $data['updatetime'] = date('Y-m-d H:i:s');
                $u->where($where)->save($data);
            }
            
            $where = array();
            $where['id'] = $uid;
            $user_info = $u->where($where)->find();
            
            if (empty($user_info))
            {
                E('获取DB用户信息失败');
            }
            
            $user_info['openid'] = $openid;
            
            session('userInfo', $user_info);
            session('openid', $openid);
            session('uid', $uid);
            
            $auth_cb_url = session('auth_callback_url');
            if ($auth_cb_url)
            {
                // 跳转到之前的页面
                redirect($auth_cb_url);
                die();
            }
        } catch (\Exception $e)
        {
            if (IS_AJAX)
            {
                $ret = array();
                $ret['status'] = $e->getCode();
                $ret['msg'] = $e->getMessage();
                $ret['content'] = array();
                $this->ajaxReturn($ret);
            } else
            {
                my_log($e->getMessage() );
                $this->error('授权失败');
            }
        }
    }
}